import {Component, OnInit, ViewChild} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {RegisterUserService} from './register-user.service';
import {Router} from '@angular/router';
import {ModalDirective} from 'ng2-bootstrap/ng2-bootstrap';
import 'select2';
import {races} from '../../constants/races';
import {politicalStatuses} from '../../constants/politicalStatuses';
import {provinces} from '../../constants/provinces';
import {technicaltitles} from '../../constants/technicaltitles';
import {educations} from '../../constants/educations';

import {validateEmail} from '../../theme/validators/email.validator';

@Component({
  selector: 'water-register-user',
  templateUrl: './register-user.html',
  styleUrls: ['./register-user.component.scss']

})
export class RegisterUserComponent implements OnInit {
  @ViewChild('smModal') successModal: ModalDirective;

  private registerUrl = '/water/userInfoSub/register';
  private enterpriseInfoUrl = '/water/enterpriseinfo/findEnterprisesByName';
  public registerForm: FormGroup;

  public registerInfo: RegisterUserInfo = new RegisterUserInfo();

  public races = races;
  public provinces = provinces;
  public politicalStatuses = politicalStatuses;
  public technicaltitles = technicaltitles;
  public educations = educations;

  private registerError = false;
  private errorMsg:string;
  private registering = false;

  private validationMessages = {
    'userSub_username': {
      'required': '请填写用户名.',
      'minlength': '用户名至少6个字符长.',
      'maxlength': '用户名不能超过20个字符.'
    },
    'userInfoSub_email': {
      'validateEmail': '邮箱格式不正确'
    },

    'password': {
      'required': '请填写密码.',
      'minlength': '密码至少6个字符长.',
      'maxlength': '密码不能超过15个字符.',
    },

    'passwordRepeat': {
      'required': '请填写确认密码.',
      'validate': '确认密码和密码不匹配.'
    },

    'userInfoSub_name': {
      'required': '请填写姓名.',
      'minlength': '姓名至少4个字符长.',
      'maxlength': '姓名不能超过24个字符.'
    },

    'userInfoSub_sex': {
      'required': '请选择性别.',
    },

    'userInfoSub_idcard': {
      'required': '请填写身份证.',
    },

    // 'userInfoSub_birthday': {
    //   'required': '请填写出生日期.',
    // },

    'userInfoSub_folk': {
      'required': '请选择民族.',
    },

    'userInfoSub_telephone': {
      'required': '请填写电话号码.',
      'minlength': '电话号码至少8个字符长.',
      'maxlength': '电话号码不能超过11个字符.'
    },

    'userInfoSub_postcode': {
      'required': '请填写邮编.'
    },
    'userInfoSub_address': {
      'required': '请填写地址.'
    },
    'userInfoSub_addressinfo': {
      'required': '请填写详细地址.'
    },
    'userInfoSub_technicaltitles': {
      'required': '请填写技术职称.'
    },
    'userInfoSub_education': {
      'required': '请填写学历.'
    },
    'userInfoSub_schoolname': {
      'required': '请填写毕业学校.'
    },

    'userInfoSub_speciality': {
      'required': '请填写专业.'
    }

  };

  private formErrors = {
    'userSub_username': '',
    'userInfoSub_email': '',
    'password': '',
    'userInfoSub_name': '',
    'userInfoSub_sex': '',
    'userInfoSub_idcard': '',
    // 'userInfoSub_birthday': '',
    'userInfoSub_folk': '',
    'userInfoSub_telephone': '',
    'userInfoSub_postcode': '',
    'userInfoSub_address': '',
    'userInfoSub_addressinfo': '',
    'userInfoSub_education': '',
    'userInfoSub_technicaltitles': '',
    'userInfoSub_schoolname': '',
    'userInfoSub_speciality': '',
    'passwordRepeat': '',
  };


  constructor(private _fb: FormBuilder,
              private _registerService: RegisterUserService,
              private _router: Router) {
  }

  public ngOnInit() {
    this.buildForm();
    this.initSelect2();
  }

  buildForm(): void {
    this.registerForm = this._fb.group(
      {
        'userSub_username': [this.registerInfo.userSub_username, [
          Validators.required,
          Validators.minLength(6),
          Validators.maxLength(20)]],
        'userInfoSub_email': [this.registerInfo.userInfoSub_email, [
          validateEmail
        ]],
        'password': [this.registerInfo.password, [
          Validators.required,
          Validators.minLength(6),
          Validators.maxLength(15),
        ]],
        'passwordRepeat': [this.registerInfo.passwordRepeat, [
          Validators.required,
        ]],

        'userInfoSub_name': [this.registerInfo.userInfoSub_name, [
          Validators.required
        ]],
        'userInfoSub_sex': [this.registerInfo.userInfoSub_sex, [
          Validators.required
        ]],
        'userInfoSub_address': [this.registerInfo.userInfoSub_address, [
          Validators.required
        ]],
        'userInfoSub_addressinfo': [this.registerInfo.userInfoSub_addressinfo, [
          Validators.required
        ]],
        'userInfoSub_education': [this.registerInfo.userInfoSub_education, [
          Validators.required
        ]],
        'userInfoSub_technicaltitles': [this.registerInfo.userInfoSub_technicaltitles, [
          Validators.required
        ]],
        'userInfoSub_province': [this.registerInfo.userInfoSub_province],
        'userInfoSub_enterpriseid': [this.registerInfo.userInfoSub_enterpriseid],
        'userInfoSub_folk': [this.registerInfo.userInfoSub_folk, [
          Validators.required
        ]],
        'userInfoSub_government': [this.registerInfo.userInfoSub_government],
        'userInfoSub_idcard': [this.registerInfo.userInfoSub_idcard, [
          Validators.required
        ]],

        'userInfoSub_postcode': [this.registerInfo.userInfoSub_postcode, [
          Validators.required,
        ]],
        'userInfoSub_schoolname': [this.registerInfo.userInfoSub_schoolname, [
          Validators.required
        ]],
        'userInfoSub_speciality': [this.registerInfo.userInfoSub_speciality, [
          Validators.required
        ]],
        'userInfoSub_telephone': [this.registerInfo.userInfoSub_telephone, [
          Validators.required,
          Validators.minLength(8),
          Validators.maxLength(11)]],
      },
      {validator: this.matchingPasswords('password', 'passwordRepeat')}
    );
    this.registerForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now

    // window.testform = this.registerForm;
  }


  onHideModal(): void {
    jQuery('.modal-backdrop').remove();
  }

  onValueChanged(data?: any) {
    if (!this.registerForm) {
      return;
    }
    const form = this.registerForm;
    for (const field in this.formErrors) {

      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
    return (group: FormGroup): {[key: string]: any} => {
      let password = group.controls[passwordKey];
      let confirmPassword = group.controls[confirmPasswordKey];

      if (password.value !== confirmPassword.value) {
        return {
          mismatchedPasswords: true
        };
      }
    }
  }

  updateDateRange(event, type:string) {
    this.registerInfo[type] = this.date2String(event.date);
  }

  private date2String(date: any): string {
    if (Object.keys(date).length === 0 || date === null || date === undefined || (date.year == 0&&date.month==0&&date.day==0)) {
      return null;
    }

    let str = date.year + '-';
    if (date.month < 10) {
      str += '0';
    }
    str += date.month + '-';

    if (date.day < 10) {
      str += '0';
    }
    str += date.day;
    return str;
  }

  public onSubmit(): void {
    let formData = this.registerForm.value;
    this.registerInfo = Object.assign(this.registerInfo, formData);
    let enterId: any = document.getElementById('enterpriseName');
    this.registerInfo.userInfoSub_enterpriseid = enterId.value;
    this.registering = true;
    this._registerService.save(this.registerUrl, this.registerInfo).then((function (body) {
      if (body.status === 'success') {
        // 注册成功
        this.registering = false;
        this.showSuccessModal();
      } else if (body.status === 'error') {
        this.registerError = true;
        this.registering = false;
        this.errorMsg = body.data;
      }
    }).bind(this), function () {
      // 注册失败
    });
  }

  showSuccessModal(): void {
    this.successModal.show();
  }

  hideSuccessModal(): void {
    this.successModal.hide();
  }

  redirect(): void {
    this._router.navigateByUrl('/login');
  }

  private initSelect2() {
    let data: any = [{id: '', text: '个人'}];
    this._registerService.getEnterpriseInfo(this.enterpriseInfoUrl).then(res => {
      let enterprises = res.data;
      for (let i = 0; i < enterprises.length; i++) {
        let item: any = {};
        item.id = enterprises[i].ids;
        item.text = enterprises[i].name;
        data.push(item);
      }

      jQuery('#enterpriseName').select2({
        data: data
      });
    });
  }

}

export class RegisterUserInfo {
  // 账号信息
  userSub_username: string;
  password: string;
  passwordRepeat: string;
  // 用户信息
  userInfoSub_address: string;
  userInfoSub_addressinfo: string;
  userInfoSub_birthday: string;
  userInfoSub_province: string;
  userInfoSub_enterpriseid: string;
  userInfoSub_finishschooldate: string;
  userInfoSub_government: string;
  userInfoSub_idcard: string;
  userInfoSub_name: string;
  userInfoSub_email: string;
  userInfoSub_postcode: string;
  userInfoSub_schoolname: string;
  userInfoSub_sex: string;
  userInfoSub_speciality: string;
  userInfoSub_telephone: string;
  userInfoSub_folk: string;
  userInfoSub_technicaltitles: string;
  userInfoSub_education: string;
}
